while


while

The instruction while is used to repeat the execution of one group of instructions while a condition is met. Thus, the number of times that the instructions will be executed is unknown.
La instrucción while es usada para repetir la ejecución de un grupo de instrucciones mientras una condición se cumpla. Así, el número de veces que las instrucciones se ejecutarán es desconocido.

Tip
Suppose for example that Mary is Richard's girlfriend. Yesterday, Mary got angry and Richard is giving her flowers as shown in the code below. In this case, Richard will keep on giving her flowers until, hopefully, Mary is not angry anymore. Observe that if the condition does not change, Richard will be stuck in this state. In real life programs, the instruction while, when used inappropriately, may stuck the program.
Suponga por ejemplo que Mary es la novia de Richard. Ayer, Mary se enojó y Richard le está llevando flores como se muestra en el código de abajo. En este caso, Richard le seguirá llevando flores a ella hasta que algún día Mary no esté enojada. Observe que si la condición no cambia, Richard permanecerá atrapado en este estado. En un programa de la vida real, la instrucción while, cuando es usada inapropiadamente, puede trabar al programa.

Program.cpp
void Program::Window_Open(Win::Event& e)
{
     Human richard;
     Human mary;
     while (mary.isAngry == true)
     {
          richard.GiveFlowers(mary);
          //Hopefully GiveFlowers changes the value of mary.isAngry
     }
}


Tip
A most healthful code is illustrated below. Here, the programmer is preventing that Richard be stuck in the state of giving flowers to Mary forever.
Una versión más saludable es ilustrada debajo. Aquí, el programador es previniendo que Richard se quede atorado en el estado de llevarle flores a Mary por siempre.

Program.cpp
void Program::Window_Open(Win::Event& e)
{
     Human richard;
     Human mary;
     int count = 0
     while (mary.isAngry == true)
     {
          richard.GiveFlowers(mary);
          count++;
          if (count >= 7) break; //Stop being such a ...
     }
}


Tip
The instruction while must include (inside its group of instructions) an instruction that modifies the condition, otherwise the instruction while will never end. For instance, in the example below, the value of i is changed inside the group of instructions and eventually the condition is not met stopping the loop.
La instrucción while debe incluir (dentro de su grupo de instrucciones) una instrucción que modifique la condición, de otro modo la instrucción while nunca terminará. Por ejemplo, en el programa mostrado debajo, el valor de i es modificado dentro del grupo de instrucciones y eventualmente la condición dejará de cumplirse deteniendo el ciclo.

while

Console Programs

A specific kind of program called console programs have a text window to interact with the user. These programs have typically a black window. To output some text so that the user can see it, these programs use the instruction cout<<. To extract some text that the user has type with the keyboard they use the instruction cin>>.

Program.cpp
// Program.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include<iostream>
using namespace std;

int _tmain(int argc, wchar_t* argv[])
{
     cout<<"Hello World";
     return 0;
}

ConsoleApplication

Tip
Console programs were the first type of computer programs and were substituted by windows programs once the operating system Microsoft Windows substituted the Disk Operating System (DOS.) In the program shown below, the instruction cout<< shows the text Type a number: in the screen. The user types a number and the instruction cin>> stores the number in the variable n. As the instructions cout<< and cin>> are inside a while, the program will keep on asking the user to type a number until the condition is not met.
Los programas de consola fueron los primeros tipos de programas de computadora y fueron sustituidos por los programa de ventana una vez que el sistema operativo Microsoft Windows sustituyera al Sistema Operativo de Discos (DOS). En el programa mostrada debajo, la instrucción cout<< muestra el texto Type a number: en la pantalla. El usuario escribe un número y la instrucción cin>> almacena el número en la variable n. Como las instrucciones cout<< y cin>> se encuentra dentro de un while, el programa seguirá pidiendo al usuario a que escriba un número hasta que la condición no se cumpla.

Problem 1
What number does the user has to type to stop the program?
Que número tiene que escribir el usuario para detener el programa?

Program.cpp
int _tmain(int argc, wchar_t* argv[])
{
     int n = 0;
     while (n == 0)
     {
          cout<<"Type a number: ";
          cin>>n;
     }     
     return 0;
}

Problem 2
What number does the user has to type to stop the program?
Que número tiene que escribir el usuario para detener el programa?

Program.cpp
int _tmain(int argc, wchar_t* argv[])
{
     int n = 0;
     while (n == 0)
     {
          cout<<"Type a number: ";
          cin>>n;
          n+=10;
     }     
     return 0;
}


Problem 3
What the number does the user has to type to stop the program?
Que número tiene que escribir el usuario para detener el programa?

Program.cpp
int _tmain(int argc, wchar_t* argv[])
{
     int n = 10;
     while (n != 0)
     {
          cout<<"Type a number: ";
          cin>>n;
          if (n == 1)
          {
               n++;
               continue;
          }
          n--;
     }     
     return 0;
}


Problem 4
Create a Wintempla Dialog application called Diego to test the following code. After creating the project, add a multiline textbox called tbxOutput.
Cree una aplicación de Diálogo de Wintempla llamada Diego para probar el código siguiente. Después de crear el proyecto, agregue una caja de texto de multilínea llamada tbxOutput.

Diego.cpp
void Diego::Window_Open(Win::Event& e)
{
     wchar_t text[64];
     double x = 220.0;
     while(x > 100.0)
     {
          _snwprintf_s(text, 64, _TRUNCATE, L"%g\r\n", x);
          tbxOutput.Text += text;
          x -= 50.0;
     }
}

Problem 5
Create a Wintempla Dialog application called Miguel to test the following code. After creating the project, add a multiline textbox called tbxOutput.
Cree una aplicación de Diálogo de Wintempla llamada Miguel para probar el código siguiente. Después de crear el proyecto, agregue una caja de texto de multilínea llamada tbxOutput.

Miguel.cpp
void Miguel::Window_Open(Win::Event& e)
{
     wchar_t text[64];
     double x = 220.0, y = 1;
     while (x > 100.0)
     {
          y *= 4.0;
          x -= 40.0;
          _snwprintf_s(text, 64, _TRUNCATE, L"%g, %g\r\n", x, y);
          tbxOutput.Text += text;
     }
}

Problem 6
Create a Wintempla Dialog application called Mora to test the following code. After creating the project, add a multiline textbox called tbxOutput.
Cree una aplicación de Diálogo de Wintempla llamada Mora para probar el código siguiente. Después de crear el proyecto, agregue una caja de texto de multilínea llamada tbxOutput.

Mora.cpp
void Mora::Window_Open(Win::Event& e)
{
     wchar_t text[64];
     int x = -1000, y = -100;
     while(x < 500.0)
     {
          _snwprintf_s(text, 64, _TRUNCATE, L"%d, %d\r\n", x, y);
          tbxOutput.Text += text;
          y += 5;
          x += 400;
     }
}


Problem 7
Create a Wintempla Dialog application called Rebeca to test the following code. After creating the project, add a multiline textbox called tbxOutput.
Cree una aplicación de Diálogo de Wintempla llamada Rebeca para probar el código siguiente. Después de crear el proyecto, agregue una caja de texto de multilínea llamada tbxOutput.

Rebeca.cpp
void Rebeca::Window_Open(Win::Event& e)
{
     wchar_t text[64];
     int x = -1000, y = -100;
     while(x < 500.0 && y < -90)
     {
          _snwprintf_s(text, 64, _TRUNCATE, L"%d, %d\r\n", x, y);
          tbxOutput.Text += text;
          y += 5;
          x += 400;
     }
}

Casting

In some case, it is necessary to convert a value from one data type to another one. In the next problem, the variable y is declared as double, and casting is used to notify the compiler that we understand that some information will be lost during the temporary conversion. If casting is not used, the compiler will generate a warning.
En algunos casos es necesario convertir un valor de un tipo de datos a otro tipo de datos. En el problema siguiente, la variable y es declarada como doble y el proceso casting es usado para notificar al compilador que entendemos que algo de información se perderá durante la conversión temporal. Si el proceso de casting no es usado, el compilador generará una advertencia.

Problem 8
Create a Wintempla Dialog application called Sister to test the following code.
Cree una aplicación de Diálogo de Wintempla llamada Sister para probar el código siguiente.

Sister.cpp
void Sister::Window_Open(Win::Event& e)
{
     int x = 3;
     wchar_t text[64];
     double y = 5.2;
     while(x > 1)
     {
          x = x + (int)y; //Casting y from double to int
          x -= 10;
     }
     _snwprintf_s(text, 64, _TRUNCATE, L"%d = %.2f", x, y);
     this->MessageBox(text, text, MB_OK);
}


© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home